<!--
/**
 * 单元名称：ArticleTweet
 * 单元功能：资讯管理/文章推文
 * 所属模块功能：资讯管理/文章推文
 * 创建人：liang
 * 创建时间：231122
 * 修改人：
 * 修改时间：
 */
 -->
<template>
  <div style="position: relative; height: 100%;">
    <m-page-list
      ref="pageListRef"
      v-loading="pageLoading"
      :style="{ 'z-index': isDia ? -1 : 0, }"
      :option="option"
      :page="page"
      :total="total"
      :table-data="tableData"
      :table-loading="tableLoading"
      v-model:value="query"
      @h-btn-click="hBtnClick"
      @col-btn-click="colBtnClick"
      @search-data="searchData"
    />

    <!-- 新增/编辑界面 -->
    <div class="dialog-wrap" :style="{ 'z-index': isDia ? 0 : -1, }" v-loading="diaLoading">
      <div class="title-wrap">
        {{ form.row_id ? '编辑' : '新增' }}文章
        <el-icon class="icon" size="16" @click="onCancel"><Close /></el-icon>
      </div>
      <div class="content-wrap">
        <el-scrollbar>
          <div class="form-wrap">
            <el-form
              ref="formRef"
              :model="form"
              :rules="rules"
              label-width="80px"
              class="demo-ruleForm"
            >
              <template v-for="(item, i) in inputList" :key="i">
                <el-form-item :label="item.label" :prop="item.prop" :required="item.required || false" >
                  <el-radio-group v-if="item.type === 'radio'" v-model="form[item.prop]">
                    <el-radio v-for="(opt, o) in item.options" :key="o" :label="opt.id">{{ opt.name }}</el-radio>
                  </el-radio-group>
                  <vue-ueditor-wrap v-else-if="item.type === 'editor'" v-model="form[item.prop]" :config="ueConfig" editor-id="editor-demo-01" />

                  <!-- <template v-else-if="item.type === 'picture'"> -->
                    <el-upload
                      v-else-if="item.type === 'picture'"
                      class="pitcure-card"
                      action="#"
                      list-type="picture-card"
                      :auto-upload="false"
                      :limit="1"
                      accept="image/*"
                      v-model:file-list="fileList"
                      :on-change="onPicChange"
                      :on-exceed="onPicExceed"
                    >
                      <template #trigger>
                        <i class="iconfont icon-tianjia"></i>
                      </template>

                      <template #file="{ file }">
                        <div class="upload-img-wrap">
                          <!-- <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" /> -->
                          <el-image
                            style="width: 100%; height: 100%;"
                            :src="file.url"
                            :zoom-rate="1.2"
                            :max-scale="7"
                            :min-scale="0.2"
                            :preview-src-list="[file.url]"
                            :initial-index="0"
                            fit="cover"
                            :preview-teleported="true"
                          />
                          <div class="upload-del-wrap" @click="onPicRemove(file)">
                            <el-icon><Close /></el-icon>
                          </div>
                          <!-- <span class="el-upload-list__item-actions">
                            <span
                              class="el-upload-list__item-preview"
                              @click="onPicPreview(file)"
                            >
                              <el-icon><zoom-in /></el-icon>
                            </span>
                            <span
                              class="el-upload-list__item-delete"
                              @click="onPicRemove(file)"
                            >
                              <el-icon><Delete /></el-icon>
                            </span>
                          </span> -->
                        </div>
                      </template>
                    </el-upload>
                  <!-- </template> -->

                  <el-input v-else-if="item.type === 'textarea'" v-model="form[item.prop]" type="textarea" :placeholder="`请输入${item.label}`" clearable />
                  <el-input v-else v-model.trim="form[item.prop]" :placeholder="`请输入${item.label}`" clearable />
                </el-form-item>
              </template>
            </el-form>
          </div>
        </el-scrollbar>
      </div>
      <div class="btn-wrap">
        <el-button type="primary" @click="onSubmit(formRef)">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, watch, } from 'vue'

import { Close, Delete, ZoomIn, Download, } from '@element-plus/icons-vue'

import MPageList from '@/components/PageList'
import { usePageList, } from '@/composables/pageList'

// import VueUeditorWrap from 'vue-ueditor-wrap'
import { uploadFile, } from '@/request/api/user'
import { postAllInfoArtice, getAllInfoArticeQueryData, delAllInfoArtice, getAllInfoArtice, putAllInfoArtice, } from '@/request/api/wechatTweet'
import { ElMessage, ElMessageBox, } from 'element-plus'

const path = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_PATH : window.webConfig.webApiBasePath,
      http = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_URL : window.webConfig.webApiBaseUrl

const {
  opts,
  option, page, total, tableLoading, tableData, query, dialogRef, dialogShow, dialogData, dialogOption,
  hBtnClick, colBtnClick, searchData, getDataList, dialogConfirm,
  getDataPage,
} = usePageListCompo()
const {
    diaLoading,
    pageListRef,
    pageLoading,
    isInit,
    isDia,
    formRef,
    inputList,
    form,
    rules,
    ueConfig,
    fileList,
    onSubmit,
    onCancel,
    onPicChange,
    onPicRemove,
    onPicExceed,
} = useDialogCompo(option)




function usePageListCompo() {
  let opts = {
        auth_id: 'department',
        idKey: 'row_id',
        getApi: getDataPage,
        delApi: delData,
      },
      {
        option, page, total, tableLoading, tableData, query, dialogRef, dialogShow, dialogData, dialogOption,
        hBtnClick, colBtnClick, searchData, getDataList, dialogConfirm,
      } = usePageList(opts)

  setOption()
  function setOption() {
    // 设置查询条件
    option.conditions = [
      { label: '开始日期',type: 'date',field_id: 'start_date', length: 'YYYY-MM-DD', col: 6},
      { label: '结束日期',type: 'date',field_id: 'end_date', length: 'YYYY-MM-DD', col: 6},
      { label: '关键词',type: 'text',field_id: 'keyword',col: 6},
      { label: '状态',type: 'picklist',field_id: 'state',col: 6,options: [
        {name: '启用',id: '1'},
        {name: '停用',id: '0'},
      ]},
    ]
    option.tableSelection = true;

    // 设置表头
    option.cols = [
      { prop: 'title', label: '标题',},
      { prop: 'source', label: '来源',},
      { prop: 'author', label: '作者',},
      { prop: 'url', label: '地址',},
      { prop: 'description', label: '描述',},
      { prop: 'state', label: '状态', /* type: 'bool', */ },
      { prop: 'input_name', label: '录入员名' },
      { prop: 'input_time', label: '录入时间' },
      { prop: 'modify_id', label: '修改员号' },
      { prop: 'modify_name', label: '修改员名' },
      { prop: 'modify_time', label: '修改时间' },
    ]
  }

  let pageParams = {}
  function getDataPage(d) {
    if(d) {
      pageParams = d
    } else {
      pageParams['page.no'] = 1
      d = pageParams
    }
    return new Promise(resolve => {
      let data = {
        ...d,
      }
      delete data['page.no']
      delete data['page.size']
      data.pagenumber = d['page.no']
      data.pagesize = d['page.size']
      if(data.state) data.state = data.state === '1'
      getAllInfoArticeQueryData(data).then(res => {
        if(res?.errcode === 0) {
          console.log(res);
          res?.row.forEach(item => {
            item.state = item.state ? '启用' : '停用'
          })
        }
        resolve(res)
      })
    })
  }
  function delData(id) {
    return new Promise(resolve => {
      delAllInfoArtice(`${opts.idKey}=${id}`).then(res => resolve(res))
    })
  }

  return {
    opts,
    option, page, total, tableLoading, tableData, query, dialogRef, dialogShow, dialogData, dialogOption,
    hBtnClick, colBtnClick, searchData, getDataList, dialogConfirm,
    getDataPage,
  }
}

function useDialogCompo(option) {
  let diaLoading = ref(false),
      pageListRef = ref(null),
      pageLoading = ref(false),
      isInit = ref(false),
      isDia = ref(false),
      formRef = ref(null),
      inputList = reactive([
        { prop: 'title', label: '标题', type: 'text', required: true, },
        { prop: 'source', label: '略缩图', type: 'picture', },
        { prop: 'source', label: '来源', type: 'text', },
        { prop: 'author', label: '作者', type: 'text', },
        { prop: 'url', label: '地址', type: 'text', },
        { prop: 'description', label: '描述', type: 'textarea', },
        { prop: 'content', label: '内容', type: 'editor', required: true, },
        { prop: 'state', label: '状态', type: 'radio', options: [
          { id: true, name: '启用', },
          { id: false, name: '停用', },
        ], },
      ]),
      newData = {
        row_id: 0,
        system_id: 0,
        artice_id: '',
        title: '',
        img_src: '',
        img_src_arr: '',
        source: '',
        author: '',
        url: '',
        description: '',
        content: '',
        state: true,
        input_id: '',
        input_name: '',
        input_time: '2099-12-31 23:59:59',
        modify_id: '',
        modify_name: '',
        modify_time: '2099-12-31 23:59:59',
      },
      form = ref({ ...newData, }),
      rules = {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur', },
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur', },
        ],
      },
      // UEDITOR_HOME_URL = process.env.NODE_ENV === 'development' ? '/UEditor/' : `${process.env.PUBLIC_PATH}UEditor/`,
      UEDITOR_HOME_URL = process.env.NODE_ENV === 'development' ? '/UEditor/' : `${window.webConfig.webSecondDir}UEditor/`,
      ueConfig = {
        // 访问 UEditor 静态资源的根路径，可参考常见问题1
        UEDITOR_HOME_URL, // 访问 UEditor 静态资源的根路径，可参考常见问题1
        // 自定义列表标号图片的地址，默认是 http://bs.baidu.com/listicon/，不过默认链接下的列表小图片都已经 404 了，所以下载了一份放到项目里啦
        listiconpath: `${UEDITOR_HOME_URL}listicon/`,

        // 编辑器不自动被内容撑搞
        autoHeightEnabled: false,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 初始容器高度
        initialFrameHeight: 540,
        // serverUrl: '//ueditor.zhenghaochuan.com/cos', // 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        // serverUrl: 'http://192.168.0.127:16004/ueditor/do',
        // serverUrl: 'http://yfgpwebapi.fszyrj.com/SchoolBus/ueditor/do',
        serverUrl: http + 'ueditor/do',

        wordCount: false,
      },
      fileList = ref([])

  watch(isDia, (newVal, oldVal) => {
    if(!isInit.value) {
      isInit.value = true
    }
  })

  resetHlBtns()
  resetColBtns()
  function resetHlBtns() {
    option.hLBtns = [
      { title: '新增', id: 'newData', type: 'primary', event: onNewData, },
      { title: '批量删除', id: 'batchDel', type: 'danger', event: onBatchDel, },
    ]
  }
  function resetColBtns() {
    option.colBtns.filter(item => item.id === 'edit')?.forEach(item => {
      item.event = onNewEdit
    })
  }
  // 新增事件
  function onNewData() {
    if(form.value.row_id) {
      form.value = { ...newData, }
      fileList.value = []
    }
    isDia.value = true
  }
  function onBatchDel() {
    let rows = pageListRef.value.getSelectionRows();
    if(!rows.length) {
      ElMessage({type: 'warning', message: '请先选择数据行'});
      return;
    }
    ElMessageBox.confirm('确定删除所选数据？', '批量删除', {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: (action) => {
        if (action === 'confirm'){
          pageLoading.value = true;

          let ids = []
          rows.forEach(item => ids.push(item.row_id))
          delAllInfoArtice(`row_id=${ids.join(',')}`).then(res => {
            pageLoading.value = false;
            if(res.errcode !== 0) return
            ElMessage({
              type: 'success',
              message: `删除成功`,
            });
            getDataList();
          })
        }
      },
    })
  }
  // 编辑
  function onNewEdit(scope, eventId) {
    let { row, } = scope
    getDetlData(row)
  }
  // 保存
  function onSubmit(formRef) {
    formRef.validate((valid, fields) => {
      if(valid) {
        let uploadPro = [],
            oldPicUrl = []
        fileList.value.forEach(item => {
          if(item.raw) uploadPro.push(uploadPicFile(item))
          else if(item.url) oldPicUrl.push(item.url)
        })
        diaLoading.value = true
        Promise.all(uploadPro).then(res => {
          let imgArr = [ ...oldPicUrl, ...res, ]
          form.value.img_src = imgArr[0] || ''
          form.value.img_src_arr = imgArr.join(',')
          let isEdit = form.value.row_id,
              reqFn = isEdit ? updateData : saveData
          reqFn().then(res => {
            diaLoading.value = false
            if(res.errcode !== 0) {
              let arr = []
              imgArr.forEach(item => arr.push({ url: item, }))
              fileList.value = arr
              return
            }
            ElMessage({
              message: `${isEdit ? '编辑' : '新增'}成功！`,
              type: 'success',
            })
            onCancel()
            getDataList()
            form.value = { ...newData, }
            fileList.value = []
          })
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  // 取消
  function onCancel() {
    isDia.value = false
  }
  function onPicChange(file, files) {

  }
  function onPicRemove(file) {
    let index = fileList.value.indexOf(file)
    fileList.value.splice(index, 1)
  }
  function onPicExceed(exceedFiles, files) {
    let index = files.length - 1,
        obj = {
          ...exceedFiles[0],
          raw: exceedFiles[0],
          url: URL.createObjectURL(exceedFiles[0]),
        }
    fileList.value.splice(index, 1, obj)
  }

  // 接口
  // 新增数据
  function saveData() {
    return new Promise(resolve => {
      postAllInfoArtice({ ...form.value, }).then(res => {
        // if(res.errcode !== 0) return
        resolve(res)
      })
    })
  }
  // 获取详情
  function getDetlData(row) {
    let { row_id, } = row
    getAllInfoArtice({
      row_id,
    }).then(res => {
      console.log(res);
      if(res.errcode !== 0) return
      isDia.value = true
      let { row, } = res

      if(row[0]) {
        let { img_src_arr, } = row[0],
            imgArr = []
        img_src_arr.split(',').forEach(item => {
          if(item) {
            imgArr.push({
              url: item,
            })
          }
        })
        fileList.value = imgArr
        form.value = row[0]
      }
    })
  }
  // 编辑数据
  function updateData() {
    return new Promise(resolve => {
      putAllInfoArtice({ ...form.value, }).then(res => {
        // if(res.errcode !== 0) return
        resolve(res)
      })
    })
  }
  function uploadPicFile(file) {
    const formData = new FormData() // FormData对象，添加参数只能通过append('key', value)的形式添加
    formData.append('file', file.raw) // 添加文件对象
    return new Promise(resolve => {
      uploadFile(formData).then(res => {
        if(res.errcode !== 0) return
        let { data, url, } = res.row[0]
        url = path + url
        resolve(url)
      })
    })
  }


  return {
    diaLoading,
    pageListRef,
    pageLoading,
    isInit,
    isDia,
    formRef,
    inputList,
    form,
    rules,
    ueConfig,
    fileList,
    onSubmit,
    onCancel,
    onPicChange,
    onPicRemove,
    onPicExceed,
  }
}
</script>

<style scoped lang='less'>
@white: #fff;

.dialog-wrap {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  // z-index: 199999;
  display: flex;
  flex-direction: column;
  background: @white;

  >.title-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid var(--el-border-color);

    >.icon:hover {
      color: var(--el-color-primary);
      cursor: pointer;

    }
  }

  >.content-wrap {
    flex: 1;
    overflow: hidden;

    .form-wrap {
      // max-width: 70rem;
      padding: 20px 7rem 20px 15px;
    }
  }

  >.btn-wrap {
    padding: 15px;
    border-top: 1px solid var(--el-border-color);
  }

  .el-upload-list__item-preview {
    position: relative;


  }
  .upload-img-wrap {
    position: relative;
    .upload-del-wrap {
      position: absolute;
      top: 0;
      right: 0;
      display: none;
      justify-content: center !important;
      align-items: center !important;
      width: 20px;
      height: 20px;
      line-height: normal !important;
      color: @white;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
    &:hover {
      .upload-del-wrap {
        display: flex !important;
      }
    }
  }
}
.pitcure-card{
  ::v-deep{
    .el-upload-list--picture-card {
      --el-upload-list-picture-card-size: 100px;
    }
    .el-upload--picture-card {
      --el-upload-picture-card-size: 100px;
    }
  }
}
</style>
<style>
.el-form-item__content .edui-editor {
  line-height: normal !important;
}
</style>
